import { Space, Button, Modal, List, Row, Col } from 'antd'
import React, { useState, useRef, useImperativeHandle } from 'react'
import './index.less'
import ConfigForm from '../config-form'
import { v4 as uuidv4 } from 'uuid';
import {
  PlusOutlined
} from '@ant-design/icons'

export const ConfigAdd = React.forwardRef(({ config, showAdd=true, showList = true, tableCom }, ref) => {
  const [isOpen, setIsOpen] = useState(false)

  const [formValue, setFormValue] = useState({
    templateCode: '',
    templateName: '',
    list: [],
  })


  const handleOpenModal = (editData) => {
    setFormValue(editData ? {...editData} : {
      templateName: '',
      templateCode: '',
      list: [],
    })
    setIsOpen(true)
  }

   // 方法暴露
   useImperativeHandle(
    ref,
    () => ({
      open() {
        handleOpenModal()
      },
    }),
    []
  )

  const configFormRef = useRef(null)

  const handleOk = () => {
    configFormRef.current.validateFields().then((value) => {
      if (formValue.key) {
        let item = config.templates.find(item => item.key === formValue.key)
        item.templateName = value.templateName
        item.templateCode = value.templateCode
        item.list = value.list
      } else {
        config.templates.push({
          key: uuidv4(),
          templateName: value.templateName,
          templateCode: value.templateCode,
          list: value.list,
        })
      }
      setIsOpen(false)
    }).catch(error => {
      console.error(error)
    })
  }

  const handleCancel = () => {
    setIsOpen(false)
  }

  // const AddCom = children ? children[0] : null

  return (
    <div className="config-pannel">
      <Space>
        {
          showAdd && <Button size='small' type="primary" icon={<PlusOutlined />} onClick={ () => handleOpenModal() }>
            新增
          </Button>
        }
      </Space>

      <Modal
        width={1300}
        title={config.title}
        open={isOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        centered
      >
        <Row gutter={12}>
          <Col span={ showList ? 20 : 24}>
            <ConfigForm ref={ configFormRef } config={config} value={formValue} onChange={setFormValue} tableCom={tableCom} />
          </Col>
          {
            showList && <Col span={4}>
              <List
                size="small"
                bordered
                dataSource={config.templates}
                renderItem={item => <List.Item>
                  <a onClick={() => handleOpenModal(item)}>{item.templateName}</a>
                </List.Item>}
              />
            </Col>
          }
        </Row>
      </Modal>
    </div>
  )
})

ConfigAdd.displayName = 'ConfigAdd'

export default ConfigAdd
